import axios from 'axios';
import type { AxiosRequestConfig, AxiosResponse } from 'axios';
import { Message } from '@arco-design/web-vue';
import { getToken } from '@/utils/auth';
import type { Result } from '@/types/global';

const instance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 30000,
});

// 请求拦截器
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // 添加token授权头
    const token = getToken();
    if (token) {
      if (!config.headers) {
        config.headers = {};
      }
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<Result<any>>) => {
    const res = response.data;
    if (res.code !== 200) {
      Message.error({
        content: res.message || '请求失败',
        duration: 5 * 1000,
      });
      return Promise.reject(new Error(res.message || '请求失败'));
    }
    return res;
  },
  (error) => {
    Message.error({
      content: error.message || '请求失败',
      duration: 5 * 1000,
    });
    return Promise.reject(error);
  }
);

const request = async <T = any>(
  config: AxiosRequestConfig
): Promise<Result<T>> => {
  const response = await instance(config);
  return response as unknown as Result<T>;
};

// 添加便捷请求方法
const extendedRequest = {
  get: <T = any>(
    url: string,
    params?: any,
    config: AxiosRequestConfig = {}
  ): Promise<Result<T>> => {
    return request({ ...config, method: 'GET', url, params });
  },
  post: <T = any>(
    url: string,
    data?: any,
    config: AxiosRequestConfig = {}
  ): Promise<Result<T>> => {
    return request({ ...config, method: 'POST', url, data });
  },
  put: <T = any>(
    url: string,
    data?: any,
    config: AxiosRequestConfig = {}
  ): Promise<Result<T>> => {
    return request({ ...config, method: 'PUT', url, data });
  },
  delete: <T = any>(
    url: string,
    data?: any,
    config: AxiosRequestConfig = {}
  ): Promise<Result<T>> => {
    return request({ ...config, method: 'DELETE', url, data });
  },
};

export default {
  ...extendedRequest,
  // 添加基础请求方法
  request: <T = any>(config: AxiosRequestConfig): Promise<Result<T>> => {
    return request(config);
  },
};
